<template>
  <van-form @submit="onSubmit" ref="myForm" validate-trigger="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="formData.code"
        name="code"
        label="券码"
        placeholder="请输入券码"
        maxlength="20"
        :clearable="true"
        :rules="[{ validator: validatorCode, message: '请输入正确格式的券码' }]"
      />
      <van-field
        v-model="formData.password"
        type="number"
        name="password"
        label="密码"
        placeholder="请输入密码"
        maxlength="10"
        :clearable="true"
        :rules="[{ validator: validatorPassword, message: '请输入正确格式的密码' }]"
      />
    </van-cell-group>
    <div class="btn-wrap" :class="{ active: isBtnActive }">
      <van-button round block type="primary" native-type="submit"> {{ btnText }} </van-button>
    </div>
  </van-form>
</template>
<script>
import { queryCouponStatus, exchangeCoupon } from '@/api/index';
import { Dialog, Toast } from 'vant';

export default {
  name: 'myForm',
  components: {},
  props: {
    btnText: {
      type: String,
      default: '确认兑换',
    },
    activeNavKey: {
      type: String,
      default: '1',
    },
  },
  data() {
    return {
      formData: {
        code: '', // 券码
        password: '', // 密码
      },
      isBtnActive: false,
    };
  },
  watch: {
    // 监听formData.code和formData.password 如果有值且验证通过则设置isBtnActive为true，反之设置为false
    formData: {
      handler() {
        const { code, password } = this.formData;
        if (this.validatorCode(code) && this.validatorPassword(password)) {
          this.isBtnActive = true;
        } else {
          this.isBtnActive = false;
        }
      },
      deep: true,
    },
    // 监听activeNavKey，如果发生变化则重置表单验证状态,并且清空表单数据
    activeNavKey() {
      this.$refs.myForm.resetValidation();
      this.formData.code = '';
      this.formData.password = '';
    },
  },
  methods: {
    onSubmit(values) {
      console.log('submit', values);
      console.log('activeNavKey', this.activeNavKey);
      if (this.activeNavKey === '1') {
        // 卡券兑换
        exchangeCoupon({
          couponCode: this.formData.code,
          couponPwd: this.formData.password,
        })
          .then((res) => {
            console.log('res', res);
            if (res.data.code === '000004') {
              // 未到兑换券的日期
              Toast.fail(res.data.msg);
              this.formData.code = '';
              this.formData.password = '';
            } else if (res.data.resData) {
              if (res.data.resData.createOrderFlag) {
                // 之前创建过订单
                Dialog.alert({
                  message: '该卡券已经兑换过啦!<br/>去查看卡券状态吧~',
                  theme: 'round-button',
                }).then(() => {
                  this.formData.code = '';
                  this.formData.password = '';
                  this.$emit('couponStatusCheck');
                });
              } else {
                // 之前未创建过订单
                Dialog.alert({
                  message: '卡券信息正确!请填写收件人信息完成兑换!',
                  theme: 'round-button',
                }).then(() => {
                  this.$store.commit('setCurrentCouponId', res.data.resData.couponId);
                  this.$router.push('/receiptman');
                });
              }
            } else {
              Toast.fail('请填写正确的券码或密码~');
            }
          })
          .catch((err) => {
            console.log('err', err);
            Toast.fail('请求失败!', JSON.stringify(err));
          });
      } else if (this.activeNavKey === '2') {
        // 状态查询
        queryCouponStatus({
          couponCode: this.formData.code,
          couponPwd: this.formData.password,
        })
          .then((res) => {
            console.log('res', res);
            if (res.data.resData) {
              console.log(res.data.resData);
              this.$emit('couponStatusShow', res.data.resData);
            } else {
              Toast.fail('请填写正确的券码或密码~');
            }
          })
          .catch((err) => {
            console.log('err', err);
            Toast.fail('请求失败!', JSON.stringify(err));
          });
      }
    },
    // 券码是20位的数字和字母(由数字和字母组成，长度为20位)
    validatorCode(value) {
      const reg = /^[a-zA-Z0-9]+$/;
      return reg.test(value);
    },
    // 密码是10位的数字
    validatorPassword(value) {
      const reg = /^[0-9]+$/;
      return reg.test(value);
    },
    // 重置表单验证状态
    resetValidation() {
      this.$refs.myForm.resetValidation();
    },
  },
};
</script>
<style lang="less" scoped>
.btn-wrap::v-deep {
  margin: 30px;
  margin-top: 70px;
  .van-button--round {
    border-radius: 6px;
  }
  .van-button--primary {
    background-color: rgba(198, 61, 28, 0.5);
    border: unset;
    height: 104px;
    .van-button__text {
      font-size: 36px;
    }
  }
  &.active {
    .van-button--primary {
      background-color: #c63d1c;
    }
  }
}
</style>
